<template>
  <section class="todoapp">
    <header class="header">
      <h1>vue3 todos</h1>
      <input 
        type="text" 
        class="new-todo" 
        v-model="newTodo" 
        placeholder="想干的事" 
        @keyup.enter="addTodo">
    </header>

    <section class="main">
      <!-- <input type="checkbox" name="" id="toggle-all" class="toggle-all"> -->

      <ul class="todo-list">
        <li class="todo" v-for="todo in todos" :key="todo.id">
          <div class="view">
            <input type="checkbox" class="toggle" v-model="todo.completed">

            <label>{{todo.title}}</label>
            <button class="destroy" @click="removeTodo(todo)"></button>
          </div>
        </li>
      </ul>
    </section>

    <footer class="footer">
      <span class="todo-count">
        <strong>{{remaining}}</strong> left
      </span>
      <button 
        class="clear-completed" 
        v-show="todos.length > remaining"
        @click="removeCompleted"
      >Clear completed</button>
    </footer>
  </section>
</template>

<script setup>
import { computed, reactive, toRefs } from "vue";

const state = reactive({
  newTodo: '',
  todos: [
    { id: 1, title:'吃饭', completed: false },
    { id: 2, title:'看电影', completed: false }
  ]
})

let { newTodo, todos } = toRefs(state)  // 把state里面的值代理出来用

function addTodo() {
  console.log(todos);
  let value = newTodo.value && newTodo.value.trim()
  if (!value) {
    return
  }
  state.todos.push({
    id: state.todos.length + 1,
    title: newTodo.value,
    completed: false
  })
  newTodo.value = ''
}

const remaining = computed(() => state.todos.filter(todo => !todo.completed).length)

function removeCompleted() {
  state.todos = state.todos.filter(todo => !todo.completed)
}

function removeTodo(item) {
  state.todos = state.todos.filter(todo => todo.id !== item.id)
}
</script>

<style>

</style>
